<template>
  <view class="warpper">
    <view class="header">
      <view class="header__left">
        <u-tabs
          :current="current"
          :list="currencyOption"
          keyName="currency"
          @change="changeTabs"
          lineHeight="0"
          itemStyle="margin-left: 0; margin-right: 50rpx; 
padding: 0;"
          activeStyle="background: #61BDB2;padding: 4rpx 16rpx;border-radius: 10rpx;color: #ffffff;"
          inactiveStyle="
background: #F6F6F6;padding: 4rpx 16rpx;border-radius: 10rpx"
        ></u-tabs>
      </view>
      <!-- <view class="header__right">
				<text @click="doHelpHandle">{{ $t('index.Help') }}</text>
				<u-icon name="error-circle-fill" color="rgba(135,135,135,0.3)" size="24rpx" class="my-icon"></u-icon>
			</view> -->
      <view class="no_tab">
        <view class="tab_btos">
          <view
            class="tab_left"
            :class="{ isSelectList: tabIndex === 1 }"
            @click="changeDirection(1)"
            >{{ $t("newDeal.defaultCollation") }}</view
          >
          <view class="money-select" @click="changeDirection(2)">
            <view
              class="select-title"
              :class="{ isSelectList: tabIndex === 2 }"
              >{{ $t("newDeal.money") }}</view
            >
            <image
              src="~@/static/image/feeServices/up.png"
              alt=""
              v-if="formParam.isAsc === 'asc'"
              class="select-direction"
              mode="heightFix"
            ></image>
            <image
              src="~@/static/image/feeServices/down.png"
              alt=""
              v-else-if="formParam.isAsc === 'desc'"
              class="select-direction"
              mode="heightFix"
            ></image>
            <image
              src="~@/static/image/feeServices/default.png"
              alt=""
              v-else
              class="select-direction"
              mode="heightFix"
            ></image>
          </view>
        </view>

        <view class="tab_right" @click="SelectCountryShow = true">
          <view class="r_ruo">{{
            releaseTradeForm.recipientCountry
              ? $t("order." + releaseTradeForm.recipientCountry)
              : $t("newDeal.selectAll")
          }}</view>
          <view class="r_img">
            <image src="@/static/image/down.png" mode=""></image>
          </view>
        </view>
      </view>
    </view>
    <scroll-view
      :scroll-top="0"
      scroll-y="true"
      class="container"
      :refresher-enabled="true"
      @refresherrefresh="refreshList"
      :refresher-triggered="refresherState"
      @scrolltolower="loadList"
    >
      <view class="container__item" v-for="(item, index) in list" :key="index">
        <view class="container__item__left">
          <view
            class="container__item__left__top"
            style="
              display: flex;
              justify-content: space-between;
              align-items: center;
            "
          >
            <image
              src="@/static/image/default-avatar.png"
              mode=""
              style="
                width: 50rpx;
                height: 50rpx;
                border-radius: 50%;
                margin-right: 20rpx;
              "
            ></image>
            <text class="number">{{ parseFloat(item.totalStock) }}</text>
            {{ item.sourceCurrencyVo.currency }}
          </view>
          <view class="container__item__left__bottom" style="color: #000000"
            >{{ $t("newDeal.country") }}:
            {{ $t("order." + item.recipientCountry) }}</view
          >
        </view>
        <view class="container__item__center" style="margin-top: 25rpx">
          <view class="container__item__center__top">
            {{ formatTime(item.createTime) }}
          </view>
          <!-- <view class="container__item__center__bottom">{{ $t('order.Name') }}: {{ item.userName }}</view> -->
        </view>
        <view class="container__item__right" @click="rechargeHandle(item)">
          {{ $t("user.Details") }}
        </view>
      </view>
    </scroll-view>
    <ConfirmPopup
      :show.sync="confirmPopupShow"
      tipType="Recharge"
      :payMoney="
        currentOrder.sourceCurrencyVo
          ? currentOrder.sourceCurrencyVo.symbol +
            parseFloat(currentOrder.totalStock)
          : parseFloat(currentOrder.totalStock)
      "
      :objValue="currentOrder"
      @confirm="confirmPaying"
    ></ConfirmPopup>
    <!-- 选择国家弹窗 -->
    <SelectPopup
      :show.sync="SelectCountryShow"
      :option="CountryOption"
      :title="$t('newDeal.selectCountry')"
      :value="releaseTradeForm.recipientCountry"
      @finish="onChangeCountry"
    ></SelectPopup>
  </view>
</template>

<script>
import {
  getTradeList,
  getCurrencyList,
  OrderTrade,
} from "@/services/bourse.js";
import ConfirmPopup from "./components/ConfirmPopup.vue";
import SelectPopup from "@/components/SelectPopup.vue";
import { getWalletList } from "@/services/user.js";
import { mapState } from "vuex";

export default {
  data() {
    return {
      releaseTradeForm: {
        tradeScene: 1,
        tradeType: 0,
        tradeDescription: "OTC交易",
        sourceCurrency: 1,
        totalStock: "",
        tradeAddressId: "",
        shelfStatus: 1, //	上架状态
        recipientCountry: "",
        exchangeDetailList: [
          {
            targetCurrencyId: 1,
            targetPrice: 1,
          },
        ],
      },
      SelectCountryShow: false,
      searchForm: {
        pageSize: 10,
        pageNum: 1,
        title: null,
        labelId: null,
        status: 1,
        orderByColumn: null,
        isAsc: null,
      },
      tabIndex: 1,
      currencyOption: [],
      current: 0,
      confirmPopupShow: false,
      list: [],
      refresherState: false,
      formParam: {
        pageSize: 10,
        pageNum: 1,
        orderByColumn: "createTime",
        // orderByColumn: "tes.stock_num",
        // desc降序 asc升序
        isAsc: "",
        recipientCountry: "",
      },
      total: 0,
      currentOrder: {},
    };
  },
  computed: {
    ...mapState(["countryList"]),
    CountryOption() {
      const local = uni.getLocale();
      const obj = {
        "zh-Hans": "cn",
        ru: "ru",
        en: "en",
      };
      return this.countryList.map((item) => {
        return {
          label: item[obj[local]],
          value: item.en,
        };
      });
      // return [
      //   {
      //     label: this.$t("order.China"),
      //     value: "China",
      //   },
      //   {
      //     label: this.$t("order.Russia"),
      //     value: "Russia",
      //   },
      // ];
    },
  },
  components: {
    ConfirmPopup,
    SelectPopup,
  },
  mounted() {
    this._getCurrencyList();
  },
  onLoad() {},
  methods: {
    // 切换默认排序和金额
    changeDirection(index) {
      // if (this.tabIndex == index) return;
      if (index == 2) {
        this.formParam.orderByColumn = "tes.stock_num";
        if (!this.formParam.isAsc) {
          this.formParam.isAsc = "asc";
        } else {
          if (this.formParam.isAsc == "asc") {
            this.formParam.isAsc = "desc";
          } else {
            this.formParam.isAsc = "asc";
          }
        }
      } else {
        this.formParam.isAsc = "";
        this.formParam.orderByColumn = "createTime";
      }

      this.tabIndex = index;
      this._getTradeList();
    },
    // 选择国家回调
    onChangeCountry(val) {
      this.releaseTradeForm.recipientCountry = val;
      this.formParam.recipientCountry = val;
      this._getTradeList();
    },
    // 获取币种
    async _getCurrencyList() {
      const { success, result } = await getWalletList();
      if (success) {
        this.currencyOption = result.rows.filter((i) => {
          return i.currencyVo.isOpen == 1;
        });
        this.currencyOption = this.currencyOption.map((it) => {
          return {
            currency: it.currencyVo.currency,
            disabled: false,
            ...it,
          };
        });
        this._getTradeList();
      }
    },
    // 交易单列表
    async _getTradeList() {
      uni.showLoading();
      const { success, result } = await getTradeList({
        sourceCurrency: this.currencyOption[this.current].currencyVo.id,
        tradeScene: 1,
        status: 1,
        shelfStatus: 1,
        ...this.formParam,
      });
      this.refresherState = false;
      this.total = result.total;
      if (success) {
        if (this.formParam.pageNum == 1) {
          this.list = result.rows;
        } else {
          this.list = [...this.list, ...result.rows];
        }
        uni.hideLoading();
      }
    },
    // 触底加载新数据
    loadList() {
      if (this.list.length < this.total) {
        this.formParam.pageNum++;
        this._getTradeList();
      }
    },
    // 下拉刷新
    refreshList() {
      this.formParam.pageNum = 1;
      this.refresherState = true;

      this._getCurrencyList();
    },
    // 确认购买回调
    async confirmPaying(val) {
      console.log("val", val);
      const obj = {
        tradeId: val.tradeId,
        tradeDetailId: val.exchangeDetailList[0].id,
      };
      console.log("obj", obj);
      const { success, result } = await OrderTrade(obj);
      if (success) {
        this.refresherState = false;
        uni.showToast({
          title: "支付成功",
          duration: 2000,
          icon: "none",
        });
        this.confirmPopupShow = false;
        uni.navigateTo({
          url: `/pagesUser/bourse/orderDetail?orderId=${result.data}&tradeType=1`,
        });
      }
    },
    // 切换标签
    changeTabs(val) {
      console.log("val", val);
      if (this.current !== val.index) {
        this.current = val.index;
        uni.showLoading();
        this.formParam.pageNum == 1;
        this.list = [];
        this._getTradeList().finally(() => {
          uni.hideLoading();
        });
      } else {
        return;
      }
    },
    // 购买
    rechargeHandle(item) {
      uni.navigateTo({
        url: `/pagesUser/recharge_details/recharge_details?id=${item.tradeId}`,
      });
      // uni.navigateTo({
      //   url: "/pagesUser/bourse/orderDetail?orderId=${result.data}&tradeType=1",
      // });
      // this.currentOrder = item;
      // this.confirmPopupShow = true;
    },
    // 格式化时间
    formatTime(val) {
      val = val.slice(2);
      val = val.slice(0, val.length - 3);
      return val.replace(/-/g, "/");
    },
  },
};
</script>

<style lang="scss" scoped>
.no_tab {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;
  margin-top: 20rpx;
  .tab_btos {
    display: flex;
    justify-content: center;
    // align-items: center;
  }
  .tab_left {
    // position: relative;
    // width: 140rpx;
    margin-right: 20rpx;
  }
  .isSelectList {
    color: #61bdb2;
    position: relative;
  }

  .isSelectList:after {
    content: "";
    width: auto;
    height: 5upx;
    background: #61bdb2;
    position: absolute;
    bottom: -15rpx;
    left: 0;
    right: 0;
    // margin: 0 auto;
  }
  .money-select {
    width: fit-content;
    display: flex;
    align-items: center;
    cursor: pointer;

    .select-title {
      font-size: 28rpx;
      font-family: HarmonyOS Sans-Regular, HarmonyOS Sans;
      font-weight: 400;
      color: #000000;
      line-height: 40rpx;
      margin-right: 10rpx;
      user-select: none;
    }

    .select-direction {
      height: 36rpx;
    }
  }
  .tab_right {
    background: #f6f6f6;
    width: 250rpx;

    height: 60rpx;
    display: flex;
    justify-content: space-around;
    align-items: center;
    .r_ruo {
      font-size: 28rpx;
      color: #878787;
    }
    .r_img {
      width: 32rpx;
      height: 32rpx;
      image {
        width: 32rpx;
        height: 32rpx;
      }
    }
  }
}
.warpper {
  height: 100%;
  font-size: 28rpx;
  font-weight: 400;
  font-family: HarmonyOS Sans-Regular, HarmonyOS Sans;

  .header {
    height: 150rpx;
    margin-bottom: 10rpx;

    &__left {
      flex: 0 0 700rpx;
      overflow: hidden;
    }

    &__right {
      flex: 0 0 200rpx;
      text-align: right;
      white-space: nowrap;
      font-size: 28rpx;
      color: rgba(135, 135, 135, 0.6);

      .my-icon {
        display: inline-block;
        margin-left: 10rpx;
      }
    }
  }

  .container {
    height: calc(100% - 150rpx);

    &__item {
      display: flex;
      justify-content: space-between;
      align-items: center;
      box-sizing: border-box;
      height: 184rpx;
      padding: 46rpx 0;
      background: #ffffff;
      box-shadow: inset 0px -2rpx 0px 0px rgba(0, 0, 0, 0.05);
      border-bottom: 2rpx solid #f6f6f6;

      &__left,
      &__center {
        display: flex;
        flex-direction: column;
        justify-content: space-between;
        height: 100%;
        font-size: 24rpx;
        color: #b3b3b3;

        &__top {
          color: #878787;
          line-height: 36rpx;

          .number {
            display: inline-block;
            color: #fe6600;
            font-weight: 600;
            font-size: 32rpx;
            margin-right: 10rpx;
          }
        }
      }

      &__right {
        padding: 16rpx;
        font-size: 28rpx;
        font-weight: 500;
        color: #ffffff;
        background-color: #61bdb2;
        border-radius: 10rpx;
      }
    }
  }
}
</style>
